Ext.define("HIT.view.UploadPanel", {
            extend          : "Ext.panel.Panel",
            alias           : "widget.fileuploadPanel",
            layout          : "fit",
            id: 'tax-upload-panel-ID',
            initComponent   : function() {
                this.width = 510;
                this.height = 300;
                this.continuous = true; // 是否连续上传，true为连续上传队列后其他文件,false只上传当前队列开始的文件
                this.setting = {
                    upload_url                   : this.uploadUrl,
                    flash_url                    : this.flashUrl,
                    file_size_limit              : "2048 MB", // 上传文件体积上限，单位MB
                    file_post_name               : "upload_file",
                    file_types                   : this.fileTypes, // 允许上传的文件类型
                    file_types_description       : "HIT Files", // 文件类型描述
                    file_upload_limit            : this.uploadLimit, // 限定用户一次性最多上传多少个文件，在上传过程中，该数字会累加，如果设置为“0”，则表示没有限制
                    file_queue_limit             : "10", // 上传队列数量限制，该项通常不需设置，会根据file_upload_limit自动赋值
                    debug                        : false,
                    post_params                  : {
                        company_name : Ext.state.Manager.get('Cxjava_company'),
                        user_name    : Ext.state.Manager.get('Cxjava_account')
                    },
                    button_cursor                : SWFUpload.CURSOR.HAND,
                    button_window_mode           : SWFUpload.WINDOW_MODE.TRANSPARENT,
                    custom_settings              : { // 自定义参数
                        scope_handler : this
                    },
                    swfupload_loaded_handler     : function() {
//                        console.log("swf init successfully");
                    }, // 当Flash控件成功加载后触发的事件处理函数
                    file_dialog_start_handler    : function() {
                    }, // 当文件选取对话框弹出前出发的事件处理函数
                    file_dialog_complete_handler : function() {
                        var me = this.customSettings.scope_handler;
                        me.linkBtnEvent();
                    }, // 当文件选取对话框关闭后触发的事件处理
                    upload_start_handler         : function() {
                    }, // 开始上传文件前触发的事件处理函数
                    upload_success_handler       : this.uploadSuccess, // 文件上传成功后触发的事件处理函数
                    upload_progress_handler      : this.uploadProgress,
                    upload_complete_handler      : this.uploadComplete,
                    upload_error_handler         : this.onFileError,
                    file_queue_error_handler     : this.onFileError,
                    file_queued_handler          : this.onQueued
                };
                this.items = [{
                            xtype   : "grid",
                            border  : false,
                            store   : Ext.create("Ext.data.Store", {
                                        model   : "HIT.model.FileModel",
                                        storeId : "fileItems"
                                    }),
                            columns : [new Ext.grid.RowNumberer(), {
                                        header       : Share.T('文件名'),
                                        width        : 200,
                                        sortable     : true,
                                        dataIndex    : 'name',
                                        menuDisabled : true
                                    }, {
                                        header       : Share.T('类型'),
                                        width        : 60,
                                        sortable     : true,
                                        dataIndex    : 'type',
                                        menuDisabled : true
                                    }, {
                                        header       : Share.T('大小'),
                                        width        : 80,
                                        sortable     : true,
                                        dataIndex    : 'size',
                                        menuDisabled : true,
                                        renderer     : this.formatFileSize
                                    }, {
                                        header       : Share.T('进度'),
                                        width        : 80,
                                        sortable     : true,
                                        dataIndex    : 'percent',
                                        menuDisabled : true,
                                        renderer     : this.formatProgressBar,
                                        scope        : this
                                    }, {
                                        header       : Share.T('状态'),
                                        width        : 120,
                                        sortable     : true,
                                        dataIndex    : 'filestatus',
                                        menuDisabled : true,
                                        renderer     : this.formatFileState,
                                        scope        : this
                                    }, {
                                        header       : '&nbsp;',
                                        width        : 40,
                                        dataIndex    : 'id',
                                        menuDisabled : true,
                                        align        : 'center',
                                        renderer     : this.formatDelBtn
                                    }]

                        }];
                this.tbar = [{
                            text : Share.T('添加文件'),
                            id   : "btnAdd",
                            icon : "resources/images/icon16/add.png"
                        }, '-', {
                            text    : Share.T('开始导入'),
                            handler : function() {
                                if (this.swfupload) {
                                    this.swfupload.displayDebugInfo();
                                    if (this.swfupload.getStats().files_queued > 0) {
                                     //   console.log($.cookie('JSESSIONID'));
                                        // this.swfupload.refreshCookies();
                                        // this.swfupload.addPostParam('JSESSIONID',
                                        // $.cookie('JSESSIONID'));
                                        // Ext.state.Manager.setProvider(new
                                        // Ext.state.CookieProvider());
                                        // Ext.state.Manager.set('JSESSIONID',
                                        // $.cookie('JSESSIONID'));
                                        this.swfupload.startUpload();
                                    }
                                }
                            },
                            scope   : this,
                            icon    : "resources/images/icon16/upload.png"
                        }, '-', {
                            text    : Share.T('停止上传'),
                            handler : function() {
//                            	if(Ext.getCmp('import-cancel')){
//                                	var StopImportItem = Ext.getCmp('import-cancel').getValue();
//                                    Ext.getCmp('import-text-file-'+StopImportItem).setValue('');
//                                }
                            	if(Ext.getCmp('import-cancel').getValue() == 1){
                            		Ext.getCmp('import-cancel').setValue(10);
                            	}else if(Ext.getCmp('import-cancel').getValue() == 2){
                            		Ext.getCmp('import-cancel').setValue(20);
                            	}else if(Ext.getCmp('import-cancel').getValue() == 3){
                            		Ext.getCmp('import-cancel').setValue(30);
                            	}else if(Ext.getCmp('import-cancel').getValue() == 4){
                            		Ext.getCmp('import-cancel').setValue(40);
                            	}else if(Ext.getCmp('import-cancel').getValue() == 5){
                            		Ext.getCmp('import-cancel').setValue(50);
                            	}
                                this.swfupload.stopUpload();
                            },
                            icon    : "resources/images/icon16/stop.png",
                            scope   : this
                        }, '-', {
                            text    : Share.T('清空列表'),
                            handler : function() {
                                this.swfupload.cancelQueue();
                                var store = Ext.data.StoreManager.lookup("fileItems");
                                store.removeAll();
                                var stats = this.swfupload.getStats();
                                var label = Ext.getCmp("queue_id");
                                label.setText(label.text = Share.T("队列中文件个数")+":" + stats.files_queued);
                            },
                            icon    : "resources/images/icon16/remove.png",
                            scope   : this
                        }, '-', {
                            xtype   : 'label',
                            id      : "queue_id",
                            text    : Share.T('队列中文件个数')+':0',
                            margins : '0 0 0 10'
                        }];
                this.bbar = [{
                            xtype : "progressbar",
                            id    : "progressBar",
                            text  : "0%",
                            width : 200
                        }, {
                            xtype : "label",
                            text  : Share.T("平均速度")+("：0kb/s"),
                            id    : "currentSpeed",
                            width : 200
                        }, '-', {
                            xtype : "label",
                            text  : Share.T("剩余时间")+"：0s",
                            id    : "timeRemaining",
                            width : 200
                        }];
                this.listeners = {
                    'afterrender' : function() {
                        var em = Ext.get(Ext.query("#btnAdd>em")[0]);
                        if (!em) {
                            // 此处为IE9以下版本的兼容问题的临时解决办法，目前还是不支持IE6
                            em = Ext.get("btnAdd-btnWrap");
                        }
                        var placeHolderId = Ext.id();
                        em.setStyle({
                                    position : 'relative',
                                    display  : 'block'
                                });
                        em.createChild({
                                    tag : 'div',
                                    id  : placeHolderId
                                });
                        this.swfupload = new SWFUpload(Ext.apply(this.setting, {
                                    button_width          : em.getWidth(),
                                    button_height         : em.getHeight(),
                                    button_placeholder_id : placeHolderId
                                }));
                        this.swfupload.uploadStopped = false;
                        Ext.get(this.swfupload.movieName).setStyle({
                                    position : 'absolute',
                                    top      : 0,
                                    left     : 0
                                });
                    }
                };

                this.callParent();
                scope : this;
                delay : 100;
            },
            onQueued        : function(file) {
                var stats = this.getStats();
                var label = Ext.getCmp("queue_id");
                label.setText(label.text = Share.T("队列中文件个数")+":" + stats.files_queued);
                var f = Ext.create("HIT.model.FileModel", {
                            id         : file.id,
                            name       : file.name,
                            type       : file.type,
                            size       : file.size,
                            filestatus : file.filestatus,
                            percent    : 0
                        });
                Ext.data.StoreManager.lookup("fileItems").add(f);
            },
            formatFileSize  : function(_v, celmeta, record) {
                return Ext.util.Format.fileSize(_v);
            },
            formatFileState : function(n) {// 文件状态
                switch (n) {
                    case SWFUpload.FILE_STATUS.QUEUED :
                        return Share.T('已加入队列');
                        break;
                    case SWFUpload.FILE_STATUS.IN_PROGRESS :
                        return Share.T('正在上传');
                        break;
                    case SWFUpload.FILE_STATUS.ERROR :
                        return '<div style="color:red;">'+Share.T('上传失败')+'</div>';
                        break;
                    case SWFUpload.FILE_STATUS.COMPLETE :
                        return Share.T('上传成功');
                        break;
                    case SWFUpload.FILE_STATUS.CANCELLED :
                        return Share.T('取消上传');
                        break;
                    default :
                        return n;
                }
            },
            formatDelBtn    : function(v) {
                return "<a href='javascript:void(0);' id='" + v
                        + "' class='swf-delete' ext:qtip='移除该文件'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a>";
            },
            linkBtnEvent    : function() {
                $(".swf-delete").on('click', {
                            swf : this.swfupload
                        }, function(e) {
                            var ds = Ext.data.StoreManager.lookup("fileItems");
                            for (var i = 0; i < ds.getCount(); i++) {
                                var rec = ds.getAt(i);
                                if (rec.get('id') == e.target.id) {
                                    ds.remove(rec);
                                    e.data.swf.cancelUpload(e.target.id, false);
                                }
                            }
                        });
            },
            onFileError     : function(file, errorCode, msg) {
                var msg = "";
          //      console.log(errorCode);
                switch (errorCode) {
                    case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED :
                        msg = Share.T('待上传文件列表数量超限，不能选择！');
                        break;
                    case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT :
                        msg = Share.T('文件太大，不能选择！文件大小不能超过') + this.settings.file_size_limit;
                        break;
                    case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE :
                        msg = Share.T('该文件大小为0，不能选择！');
                        break;
                    case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE :
                        msg = Share.T('该文件类型不可以上传！');
                        break;
                    case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED :
                        msg = Share.T("上传已经停止");
                        break;
                    case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED :
                        msg = Share.T("所有文件都已清空！");
                        break;
                    default :
                        msg = Share.T("未知错误!");
                        break;
                }
                Ext.Msg.show({
                            title   : Share.T('提示'),
                            msg     : msg,
                            width   : 280,
                            icon    : Ext.Msg.WARNING,
                            buttons : Ext.Msg.OK

                        });
            },
            uploadProgress  : function(file, bytesComplete, totalBytes) { // 处理进度条
                // console.log("完成百分比" + file.percentUploaded + "，当前速度" +
                // file.currentSpeed / 8 / 1024 / 1024 + "MB/s");
                // console.log(SWFUpload.speed.formatBytes(bytesComplete));
                var ds = Ext.data.StoreManager.lookup("fileItems");
                for (var i = 0; i < ds.getCount(); i++) {
                    var record = ds.getAt(i);
                    if (record.get('id') == file.id) {
                        record.set('percent', file.percentUploaded);
                        record.set('filestatus', file.filestatus);
                        record.commit();
                    }
                }
                // 更新进度条
                var pb = Ext.getCmp("progressBar");
                pb
                        .updateProgress(file.percentUploaded / 100,
                                SWFUpload.speed.formatPercent(file.percentUploaded), true
                        );
                // 更新当前速度
                var speed = Ext.getCmp("currentSpeed");
                var speedNum = Math.ceil(file.averageSpeed / 8 / 1024);
                // console.log(Math.ceil(2.8));
                var unit = speedNum / 1024 < 0 ? "KB/s" : "MB/s";
                var speedValue = speedNum / 1024 < 0 ? speedNum : speedNum / 1024;
                speedValue = Math.ceil(speedValue);
                speed.setText(Share.T("平均速度")+":" + speedValue + unit);
                // 更新剩余时间
                var timeRemaining = Ext.getCmp("timeRemaining");
                timeRemaining.setText(Share.T("估计剩余时间")+":" + SWFUpload.speed.formatTime(file.timeRemaining));

            },
            uploadComplete  : function(file) {
                var me = this;
//                var tabPanel = Ext.getCmp('centertabpanel');
//                var obj = tabPanel.getActiveTab();
//                if (obj.id == 'tab-set-account') {
//                    var win = me.customSettings.scope_handler.up('window');
//                    win.close();
//                    Ext.Msg.alert(Share.getMsg('alert'), '科目导入成功');
//                    Ext.getCmp('tab-set-account').getStore().reload();
//                    return;
//                }
//                else if (obj.id == 'tab-set-mapping') {
//                    var win = me.customSettings.scope_handler.up('window');
//                    win.close();
//                    Ext.Msg.alert(Share.getMsg('alert'), '科目映射导入成功');
//                    Ext.getCmp('tab-set-mapping').getStore().reload();
//                    return;
//                }
//                else if (obj.id == 'tab-set-tcode') {
//                    var win = me.customSettings.scope_handler.up('window');
//                    win.close();
//                    Ext.Msg.alert(Share.getMsg('alert'), 'TCODE导入成功');
//                    Ext.getCmp('tab-set-tcode').getStore().reload();
//                    return;
//                }

                var store = Ext.data.StoreManager.lookup("fileItems");
                // console.log(store);
                model = store.getById(file.id);
                model.set("filestatus", file.filestatus);
                model.commit();
                // console.log(model);
                // console.log(this.customSettings.scope_handler.continuous);  
                var stats = this.getStats();
                // console.log(stats);
                if(stats != undefined && stats != null && stats != '' ){
	                var label = Ext.getCmp("queue_id");
	                label.setText(label.text = Share.T("队列中文件个数")+":" + stats.files_queued);
	
	                if (this.customSettings.scope_handler.alldone && this.getStats().files_queued === 0
	                /*
	                 * && this.getStats().successful_uploads ===
	                 * store.data.items.length
	                 */) {
	
	                    var uploadfiles = store.data.items[0].data.name;
	                    var i = 1;
	                    for (; i < store.data.items.length; i++) {
	                        uploadfiles = uploadfiles + ';' + store.data.items[i].data.name;
	                    }
	//                    console.log(uploadfiles);
	                //    console.log(me.customSettings.scope_handler.newFileNames);
	//                    console.log("FILE_TYPE: "+Ext.getCmp('import-file-type').getValue());
	//                    console.log("TTT: "+Ext.getCmp('import-label-file-1').title);
	                    if(Ext.getCmp('import-file-type').getValue() == '1' && Ext.getCmp('import-cancel').getValue() != 10){  //EXT的并且为&&，或为||
	                    	Ext.getCmp('import-text-file-1').setValue(uploadfiles);  //LOCAL_FILE_NAME
	                    	Ext.getCmp('import-file-db1').setValue(me.customSettings.scope_handler.newFileNames.join(";"));  //SERVER_FILE_NAME
	                    }else{
	//                    	Ext.getCmp('import-text-file-1').setValue('');  规则：当TESTFIELD中有文件时，再次上传&并取消则清空TEXTFIELD
	                    }
	                    if(Ext.getCmp('import-file-type').getValue() == '2' && Ext.getCmp('import-cancel').getValue() != 20){
	                    	Ext.getCmp('import-text-file-2').setValue(uploadfiles);
	                    	Ext.getCmp('import-file-db2').setValue(me.customSettings.scope_handler.newFileNames.join(";"));
	                    }else{
	//                    	Ext.getCmp('import-text-file-2').setValue('');
	                    }
	                    if(Ext.getCmp('import-file-type').getValue() == '3' && Ext.getCmp('import-cancel').getValue() != 30){
	                    	Ext.getCmp('import-text-file-3').setValue(uploadfiles);
	                    	Ext.getCmp('import-file-db3').setValue(me.customSettings.scope_handler.newFileNames.join(";"));
	                    }else{
	//                    	Ext.getCmp('import-text-file-3').setValue('');
	                    }
	                    if(Ext.getCmp('import-file-type').getValue() == '4' && Ext.getCmp('import-cancel').getValue() != 40){
	                    	Ext.getCmp('import-text-file-4').setValue(uploadfiles);
	                    	Ext.getCmp('import-file-db4').setValue(me.customSettings.scope_handler.newFileNames.join(";"));
	                    }else{
	//                    	Ext.getCmp('import-text-file-4').setValue('');
	                    }
	                    if(Ext.getCmp('import-file-type').getValue() == '5' && Ext.getCmp('import-cancel').getValue() != 50){
	                    	Ext.getCmp('import-text-file-5').setValue(uploadfiles);
	                    	Ext.getCmp('import-file-db5').setValue(me.customSettings.scope_handler.newFileNames.join(";"));
	                    }else{
	//                    	Ext.getCmp('import-text-file-5').setValue('');
	                    }
	//                    me.customSettings.scope_handler.up('window').close();
	//                    Ext.getCmp('import-file-task-tax').close();
	                    if(Ext.getCmp('import-file-type').getValue() != -1){
	                    	Ext.getCmp('import-file-task-tax').close();
	                    }else{
	                    	Share.AjaxRequest({
	                    		    url      : ctx + '/uploadalldone;jsessionid=' + $.cookie('JSESSIONID'),
	                                params   : {
	                                    filenames      : uploadfiles
	                                   ,new_file_names  : me.customSettings.scope_handler.newFileNames.join(";")
	                                },
	                                showMsg  : false,
	                                callback : function(json) {                                    
	                                    me.customSettings.scope_handler.alldoneFun(json);
	                                    
	                                    // var store =
	                                    // Ext.data.StoreManager.lookup("fileItems");
	                                    // store.removeAll();
	                                    // var stats=this.swfupload.getStats();
	                                    // var label=Ext.getCmp("queue_id");
	                                    // label.setText(label.text="队列中文件个数:0");
	//                                    Ext.Msg.alert(Share.getMsg('alert'), '文件上传成功');
	//                                    var win = me.customSettings.scope_handler.up('window');
	//                                    win.close();
	//                                    Ext.getCmp('tab-import-file').getStore().reload();
	                                },
	                                falseFun : function(json) {// 失败后想做的个性化操作函数
	                                    me.customSettings.scope_handler.alldoneFun(json);
	                                }
	                            });
	                    }
	                    
	                }
	
	                return this.customSettings.scope_handler.continuous;
            	}
            }
        });
